<template>
	<view>
		<view class="content-header">
			<!-- <view class="title-name">
                请选择收货地址
            </view> -->

			<uni-forms :modelValue="formData" v-if="!saveOrEdit&&addressData.name">
				<view class="input-wrapper">
					<view class="title-text">姓名</view>
					<u-input style="color: white;" id="uni-input-type-text" class="uni-input" type="text"
						v-model="addressData.name" placeholder="请输入收货人姓名" @blur="validateName" />
				</view>
				<view class="error-message" v-if="nameError">{{ nameError }}</view>
				<view class="input-wrapper">
					<view class="title-text" style="position: relative">
						<text>电话 +86</text>
						<view class="select"><u-icon name="arrow-down-fill" color="#372928" size="15"></u-icon></view>
					</view>
					<u-input id="uni-input-type-text" class="uni-input" type="text" v-model="addressData.phone"
						placeholder="请输入收货人手机号" @blur="validatePhone" />
				</view>
				<view class="error-message" v-if="phoneError">{{ phoneError }}</view>

				<view class="input-wrapper" @click="openMultiLevelSelect()">
					<view class="title-text">所在地区</view>
					<view class="input selectcity">
						<view style="padding: 0 20rpx 0 35rpx;" :style="{color:addressData.address?'#333':'#aaa'}">
							{{addressData.address?addressData.address:'请选择省市区'}}
						</view>
						<!-- <u-input placeholder="请选择省市区" type="text" v-model="addressData.address" /> -->
						<!-- <image src="/static/right.png" class="rights"></image> -->
					</view>
				</view>
				<view class="input-wrapper">
					<view class="title-text">详细地址</view>
					<u-input id="uni-input-type-text" v-model="addressData.addressDetail" class="uni-input" type="text"
						placeholder="请输入道路,小区,门牌号等" />
				</view>
				<view class="input-wrapper">
					<view class="title-text">设为默认地址</view>
					<view class="uni-padding-wrap">
						<view @click="confirmOrCancel">
							<label class="radio">
								<radio value="r1" :checked="addressData.isDefault" />
							</label>
						</view>
					</view>
				</view>
			</uni-forms>
			<uni-forms :modelValue="formData" v-else-if="saveOrEdit">
				<view class="input-wrapper">
					<view class="title-text">姓名</view>
					<u-input style="color: white;" id="uni-input-type-text" class="uni-input" type="text"
						v-model="addressData.name" placeholder="请输入收货人姓名" @blur="validateName" />
				</view>
				<view class="error-message" v-if="nameError">{{ nameError }}</view>
				<view class="input-wrapper">
					<view class="title-text" style="position: relative">
						<text>电话 +86</text>
						<view class="select"><u-icon name="arrow-down-fill" color="#372928" size="15"></u-icon></view>
					</view>
					<u-input id="uni-input-type-text" class="uni-input" type="text" v-model="addressData.phone"
						placeholder="请输入收货人手机号" @blur="validatePhone" />
				</view>
				<view class="error-message" v-if="phoneError">{{ phoneError }}</view>

				<view class="input-wrapper" @click="openMultiLevelSelect()">
					<view class="title-text">所在地区</view>
					<view class="input selectcity">
						<view style="padding: 0 20rpx 0 35rpx;" :style="{color:addressData.address?'#333':'#aaa'}">
							{{addressData.address?addressData.address:'请选择省市区'}}
						</view>
						<!-- <u-input placeholder="请选择省市区" type="text" v-model="addressData.address" /> -->
						<!-- <image src="/static/right.png" class="rights"></image> -->
					</view>
				</view>
				<view class="input-wrapper">
					<view class="title-text">详细地址</view>
					<u-input id="uni-input-type-text" v-model="addressData.addressDetail" class="uni-input" type="text"
						placeholder="请输入道路,小区,门牌号等" />
				</view>
				<view class="input-wrapper">
					<view class="title-text">设为默认地址</view>
					<view class="uni-padding-wrap">
						<view @click="confirmOrCancel">
							<label class="radio">
								<radio value="r1" :checked="addressData.isDefault" />
							</label>
						</view>
					</view>
				</view>
			</uni-forms>
		</view>

		<!-- <view class="page">
          <view class="page-description">多级联选择器 API</view>
          <view class="page-section">
            <view class="page-section-title">my.multiLevelSelect</view>
            <view class="page-section-demo">
              <button type="primary" @click="openMultiLevelSelect()">多级联选择器</button>
            </view>
          </view>
        </view> -->

		<button @click="submit" :disabled="!isFormValid" style="
				width: 354rpx;
				height: 60rpx;
				background-color: red;
				margin: 234rpx auto;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: #1677ff;
				border-radius: 25rpx;
				color: white;
			">
			保存
		</button>
		<!-- <u-picker :show="show" ref="uPicker" :columns="columns" @confirm="confirm" @cancel="close"></u-picker> -->
		<!-- <u-picker :show="show" ref="uPickerRef" :columns="columns" @confirm="confirm" @change="changeHandler" @cancel="close"></u-picker> -->
	</view>
</template>

<script>
	// import address from "@/api/address.js";
	import address from "@/api/address.js";
	export default {
		data() {
			return {

				nameError: '',
				phoneError: '',
				countryCode: '+86',
				countryCodes: ['+86', '+852', '+853', '+886'],
				isRadioShow: 0,
				addressList: {},
				codeData: [],
				addressData: {
					name: "",
					phone: "",
					province: "",
					provinceName: "",
					city: "",
					cityName: "",
					district: "",
					districtName: "",
					addressDetail: "",
					longitude: "",
					latitude: "",
					isDefault: 0,
					address: ""
				},
				show: false,
				isShow: true,
				saveOrEdit: true, //编辑或者保存
			};
		},
		computed: {
			// 表单是否有效
			isFormValid() {
				return !this.nameError && !this.phoneError &&
					this.addressData.name.trim() !== '' &&
					this.addressData.phone.trim() !== '';
			}
		},
		onLoad(option) {
			this.getlangitudeList();
			if (option.data) {

				const res = JSON.parse(option.data);
				console.log(res, "数据")
				Object.assign(this.addressData, res)
				this.addressData.address = res.provinceName + res.cityName + res.districtName
				// setTimeout(()=>{
				// 	    this.addressData = res

				// 	    
				// },500)

			}

			if (option.id) {
				this.getAddressInfo(Number(option.id));
				this.saveOrEdit = false; //编辑或保存为非

			} else {
				uni.setNavigationBarTitle({
					title: "新建地址",
				});
				this.saveOrEdit = true; //编辑或保存为真
			}
		},
		methods: {
			formatAddressData(data) {
				return data.map(province => ({
					name: province.cityName,
					id: province.id,
					subList: province.leaseChinaVos.map(city => ({
						name: city.cityName,
						city: city.id,
						subList: city.leaseChinaVos.map(area => ({
							name: area.cityName,
							district: area.id,
							latitude: area.latitude,
							longitude: area.longitude
						}))
					}))
				}));
			},
			openMultiLevelSelect() {


				const formatData = this.formatAddressData(this.addressList);
				console.log(formatData, "数据")
				// #ifdef MP-ALIPAY
				my.multiLevelSelect({
					title: '请选择省/市/区',
					list: formatData,
					success: (res) => {
						const selectedPath = res.result.map(item => item.name).join(' > ');
						console.log(res)
						//数据回显

						//收集数据
						this.codeData = res.result[0];
						this.addressData.province = res.result[0].input.id
						this.addressData.provinceName = res.result[0].name
						this.addressData.city = res.result[1].input.city
						this.addressData.cityName = res.result[1].input.name
						this.addressData.district = res.result[2].input.district
						this.addressData.districtName = res.result[2].name
						this.addressData.latitude = res.result[2].input.latitude
						this.addressData.longitude = res.result[2].input.longitude
						this.addressData.address = this.addressData.provinceName + this.addressData.cityName +
							this.addressData.districtName
						console.log(this.addressData)
						console.log(this.addressData.address)
						console.log("你选择了", res)
						// uni.showToast({
						//   title: `您选择了：${selectedPath}`,
						//   icon: 'none'
						// });
					},
					fail: (err) => {
						console.error('选择器调用失败:', err);
					}
				});
				// #endif

				// #ifndef MP-ALIPAY
				uni.showToast({
					title: '当前平台不支持多级选择器',
					icon: 'none'
				});

				// 数据格式转换（适配支付宝多级选择器）
				formatAddressData(data) {
					return data.map(province => ({
						name: province.cityName,
						subList: province.leaseChinaVos.map(city => ({
							name: city.cityName,
							subList: city.leaseChinaVos.map(area => ({
								name: area.cityName

							}))
						}))
					}));
				}
				// #endif
			},

			//获取全国经纬度
			getlangitudeList() {
				address
					.assemblyList()
					.then((res) => {
						this.addressList = res.data
						this.addressList.forEach((item, index) => {
							// console.log(item.leaseChinaVos[0].cityName)
							console.log(item.leaseChinaVos[0].leaseChinaVos[0].cityName)
							// console.log(item.cityName)
						})
						console.log(this.addressList)
						console.log(res, "resk...")

					})
					.catch((erro) => {
						console.log('error');
					});
			},
			// 验证姓名
			validateName() {
				const name = this.addressData.name.trim();

				if (!name) {
					this.nameError = '请输入收货人姓名';
					return false;
				}

				// 简单验证：至少包含2个字符
				if (name.length < 2) {
					this.nameError = '姓名至少包含2个字符';
					return false;
				}

				// 清除错误
				this.nameError = '';
				return true;
			},

			// 验证手机号
			validatePhone() {
				const phone = this.addressData.phone.trim();

				if (!phone) {
					this.phoneError = '请输入收货人手机号';
					return false;
				}

				// 手机号正则（根据国家码选择不同的正则）
				const phoneRegex = /^1[3-9]\d{9}$/; // 中国大陆手机号

				if (!phoneRegex.test(phone)) {
					this.phoneError = '请输入有效手机号';
					return false;
				}

				// 清除错误
				this.phoneError = '';
				return true;
			},

			// 选择国家码
			selectCountryCode() {
				uni.showActionSheet({
					itemList: this.countryCodes,
					success: (res) => {
						this.countryCode = this.countryCodes[res.tapIndex];
						// 根据国家码切换手机号验证规则
						this.updatePhoneValidation();
					}
				});
			},

			// 根据国家码更新手机号验证规则
			updatePhoneValidation() {
				// 这里可以根据不同国家码设置不同的验证规则
				if (this.countryCode === '+86') {
					// 中国大陆
					this.phoneRegex = /^1[3-9]\d{9}$/;
				} else if (this.countryCode === '+852') {
					// 中国香港
					this.phoneRegex = /^[5689]\d{7}$/;
				}
				// 其他国家码...

				// 如果已有输入，重新验证
				if (this.addressData.phone) {
					this.validatePhone();
				}
			},

			// 提交表单
			submitForm() {
				//保存地址


				// 再次验证确保所有字段都有效
				const isNameValid = this.validateName();
				const isPhoneValid = this.validatePhone();

				if (isNameValid && isPhoneValid) {
					// 表单有效，执行提交逻辑
					console.log('提交表单数据:', this.addressData);

					// 模拟提交成功
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});

					// 重置表单
					this.resetForm();
				}
			},

			// 重置表单
			resetForm() {
				this.addressData = {
					name: '',
					phone: ''
				};
				this.nameError = '';
				this.phoneError = '';
			},




			confirmOrCancel() {

				// this.isRadioShow = !this.isRadioShow;
				if (this.addressData.isDefault) {
					this.addressData.isDefault = 0;
				} else {
					this.addressData.isDefault = 1;
				}
			},

			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					this.$refs.uPickerRef.setColumnValues(1, this.columnData[index])
				}
			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {

				this.show = false;
			},
			close() {
				this.show = false;
			},


			getAddressInfo(id) {

				address.getAddressById(id).then((res) => {

					//省市区
					// console.log("address=>",address);
					console.log(res)
					// this.addressData.provinceName = res.data.provinceName;
					Object.assign(this.addressData, res.data)
					this.addressData.address = res.data.provinceName + res.data.cityName + res.data.districtName


					//   this.addressData.cityName = res.data.city;
					//    this.addressData.districtName = res.data.districtName;
					// {
					// 	name,
					// 	phone,
					// 	province,
					// 	provinceName,
					// 	city,
					// 	cityName,
					// 	district,
					// 	districtName,
					// 	addressDetail,
					// 	longitude,
					// 	latitude,
					// } = res.data;

					// this.$nextTick(()=>{

					// })

					// console.log(  this.addressData ,"djsioahdiasidhasdhsadh")
					//        console.log("123",this.addressData.isDefault)
					//    this.addressData.address = res.data.provinceName + res.data.cityName + res.data.districtName;

					return





				});
			},
			submit() {

				if (this.addressData.name == "" || this.addressData.phone == "" || this.addressData.districtName == "" ||
					this.addressData.addressDetail == "") return uni.showToast({
					title: "数据必须填完整！",
					icon: "none",
				});

				// this.addressData.district = this.addressData.area;
				if (this.saveOrEdit) { //如果编辑或保存为真
					//新增地址
					address.saveAddress(this.addressData).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: "保存成功！",
								icon: "none",
							});
							console.log("发送消息")
							uni.$emit('addAddress', {});
							setTimeout(() => {
								uni.navigateBack();
							}, 500)

						}
					});

				} else { //如果编辑或保存为非
					address.updateAddress(this.addressData).then((res) => {
						if (res.code == 200) {
							uni.showToast({
								title: "保存成功！",
								icon: "none",
							});
							uni.$emit('addAddress', {});
							setTimeout(() => {
								uni.navigateBack();
							}, 500)
						}
					});
				}
			},
			openPicker() {
				this.show = true; //下拉遮罩层
			},

			changeClick(value, value2, value3, value4) {
				// console.log("地址选择器 = " + value + value2 + value3);
				console.log("地址选择器 = ", value, value2, value3, value4);
				// console.log("地址选择器44 = " + value4);
				// console.log("地址选择器44 = " + value5);
				// console.log("地址选择器44 = " + value6);
				this.addressData.province = value;
				this.addressData.city = value2;
				this.addressData.district = value3;
			},
			onhideShow() {
				this.show = false;
			},
			//选中省市区
			onsetCity(e) {

				console.log(e, 'eeeeeeeeee');
				let data = e.detail.target.dataset;
				let address = data.province + data.city + data.area;
				this.show = false;
				this.addressData.address = address;
			},
			switchChange(e) {
				// console.log("e----", e);
				if (e.addressDetail.value) {
					this.addressData.isDefault = 0;
				} else {
					this.addressData.isDefault = 1;
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.content-header {
		box-sizing: border-box;
		padding-left: 59rpx;
	}

	.select {
		position: absolute;
		right: 30rpx;
		top: 0rpx;
	}

	.title-name {
		font-size: 32rpx;
		color: #333333;
		font-weight: 600;
		margin: 32rpx 0;
	}

	.item-address {
		width: 398rpx;
		margin-left: 62rpx;
		color: #777777;
	}

	.selected-item {
		width: 100%;
		margin: 38rpx 0;
		font-size: 30rpx;
		position: relative;
	}

	.addAdress {
		color: #777777;
		display: flex;
	}

	.input-wrapper {
		display: flex;
		height: 40rpx;
		align-items: center;
		margin: 58rpx 0;
	}

	.title-text {
		width: 198rpx;
	}

	.error-message {
		color: #f56c6c;
		font-size: 12px;
		margin-top: 5px;
	}
</style>